CLANG_FORMAT ?= clang-format
CLANG_FORMAT_DIFF ?= clang-format-diff

.PHONY: all check check-style check-style-show check-style-fix clean generate-code generate-docs

all:
	if [ ! -d "builddir" ]; then \
		meson setup builddir; \
	fi; \
	meson compile -C builddir pkcs11

check:
	meson test -C builddir

clean:
	rm -rf builddir

check-style:
	@lines=`git diff -U0 --no-color --relative origin/main -- ':!src/pkcs11.h' | $(CLANG_FORMAT_DIFF) -p1 |wc -l`; \
	if [ "$$lines" != "0" ]; then \
		echo "Coding Style issues detected"; \
		exit 1; \
	else \
		echo "Coding Styles checks out"; \
	fi

check-style-show:
	git diff -U0 --no-color --relative origin/main -- ':!src/pkcs11.h' | $(CLANG_FORMAT_DIFF) -p1

check-style-fix:
	git diff -U0 --no-color --relative origin/main -- ':!src/pkcs11.h' | $(CLANG_FORMAT_DIFF) -i -p1

shellcheck:
	shellcheck -P tests -e SC2016 tests/*.sh tests/test-wrapper tests/t{basic,certs,cms,democa,digest,ecc,ecdh,ecxc,edwards,forking,hkdf,imported,oaepsha2,op_state,pem_encoder,pinlock,pubkey,rand,rsa,rsapss,rsapssam,tls,tlsfuzzer,uri}

generate-code:
	for pfile in src/*.pre; do \
		gfile=`echo $${pfile} | sed s/\.pre/\.gen\.c/`; \
		echo "/* DO NOT EDIT, autogenerated from $${pfile} */" > "$${gfile}"; \
		echo "/* Modify $${pfile} then run make generate-code */" >> "$${gfile}"; \
		cat $${pfile} | $(CC) $(CFLAGS) -E - | grep -v "^#" > "$${gfile}.tmp"; \
		sed -i -n -e '/^BEGIN:$$/,$$p' "$${gfile}.tmp"; \
		sed -i 's/^BEGIN:$$//' "$${gfile}.tmp"; \
		cat "$${gfile}.tmp" >> $${gfile}; \
		$(CLANG_FORMAT) -i --verbose "$${gfile}"; \
		rm "$${gfile}.tmp"; \
	done

generate-docs:
	for mdfile in docs/*.md; do \
		echo "Processing $${mdfile}"; \
		manfile=`echo $${mdfile} | sed s/\.md//`; \
		pandoc --standalone --to man $${mdfile} -o $${manfile}; \
	done

dist:
	rm -fr distdir
	meson setup distdir
	meson compile -C distdir pkcs11
	meson test -C distdir
	meson dist -C distdir
